package com.myblog.service;

import com.myblog.mapper.ArticleMapper;
import com.myblog.entity.Article;
import com.myblog.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * 定时读取文章阅读量写入数据库
 */
@Service
@Slf4j
public class ScheduledService {

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private ArticleMapper articleMapper;

    @Async //异步执行
    @Scheduled(cron = "0 0 */2 * * ?") //每隔两个小时执行一次
    public void update() {

        Map map = redisUtil.hentries("BLOG:ARTICLE_VIEW");
        for (Object key : map.keySet()) {


            Integer id = Integer.parseInt(key.toString());
            Integer view = Integer.parseInt(map.get(key).toString());
            Article article = new Article();
            article.setId(id);
            article.setViews(view);
            articleMapper.updateById(article);
        }

        log.info("Scheduled : {}", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "|将阅读量写入数据库");
    }

}
